package com.lkm.app_ui.m.Imple.goods;

import com.google.gson.annotations.SerializedName;
import com.lkm.app.event.OnNetworkStateEvent;
import com.lkm.app_ui.AppConfig;
import com.lkm.app_ui.AppConst;
import com.lkm.app_ui.RunTimeData;
import com.lkm.app_ui.help.GsonHelp;
import com.lkm.app_ui.m.goods.GoodsEntity;
import com.lkm.comlib.fun_m.NetworkStateModule;
import com.lkm.comlib.task2.DefaultTaskExecutor;
import com.lkm.frame.entity.ResponEntityAbs;
import com.lkm.frame.file.FileHelper;
import com.lkm.frame.otto.LinkBus;
import com.lkm.frame.otto.ObserverAutoNext;
import com.lkm.frame.task.ProgressDataImpl;
import com.lkm.frame.task2.Task;
import com.lkm.frame.task2.TaskAdapter;
import com.lkm.javatool.StringHelp;
import com.lkm.market2_0.entity.ResponEntity;
import com.lkm.market2_0.netapi.Api;

import java.io.File;
import java.util.List;
import java.util.regex.Pattern;



class HoldGoodsInfoTask extends TaskAdapter<Void, GoodsBO, ResponEntityAbs<GoodsBO>> {

    public static Task<Void, GoodsBO, ResponEntityAbs<GoodsBO>> start(boolean isHold) {
        HoldGoodsInfoTask task = new HoldGoodsInfoTask(isHold);
        task.action();
        task.setParam(null);
        task.execTask();
        return task;
    }

    private boolean isHold;

    public HoldGoodsInfoTask(boolean isHold) {
        super(new DefaultTaskExecutor(AppConst.getTaskExecutor(), true), HoldGoodsInfoTask.class.getName(), AppConst.getTaskManager2());
        this.isHold = isHold;
    }

    @Override
    public void doExecuting(Void param) {
        super.doExecuting(param);
        mTaskExecutor.executor(new Runnable() {
            @Override
            public void run() {
                ayncdoExecuting();
            }
        });
    }

    private GoodsBO toGoodsBO(GoodsTO goodsTO){
        GoodsBO goodsBO = new GoodsBO();
        goodsBO.rulePattern = StringHelp.isEmpty(goodsTO.rule) ? null : Pattern.compile(goodsTO.rule);

        goodsBO.ruleVarIndex = GsonHelp.fromJson(goodsTO.ruleVar, GoodsBO.RuleVarIndex.class);
        goodsBO.goodsEntities = goodsTO.goodsEntities;

        return goodsBO;
    }



    private void ayncdoExecuting() {

        String json = Api.getGoods("" + RunTimeData.steelyardInfo.getOrg(), RunTimeData.LoaclSteelyardMac, this);

        ResponEntity<GoodsTO> responEntity = ResponEntity.fromJson(json, new com.google.gson.reflect.TypeToken<GoodsTO>() {
                }.getType()
                , "");

        if (responEntity.isSuccess()) {

            GoodsTO goodsTO = responEntity.getData();
            ResponEntity<GoodsBO> goodsBORe = ResponEntity.success(toGoodsBO(goodsTO));

            complete(goodsBORe);

            
            FileHelper.SaveString(json,new File(AppConfig.DataFile.getDataFile("goods.json")),AppConst.charset,true);
        } else {
            json = FileHelper.getString(new File(AppConfig.DataFile.getDataFile("goods.json")),AppConst.charset);

            responEntity = ResponEntity.fromJson(json, new com.google.gson.reflect.TypeToken<GoodsTO>() {
                    }.getType(), "");
            if (responEntity.isSuccess()) {
                GoodsTO goodsTO = responEntity.getData();
                progressUpdate(new ProgressDataImpl<GoodsBO>(0,0,toGoodsBO(goodsTO)));
            }


            
            if (isHold && json == null) {
                requestRe();
            } else {
                complete(new ResponEntity<GoodsBO>().fail(null, responEntity.getMsg()));
            }

        }

    }

    
    int isReForNetOK = 0;

    private void requestRe() {
        if (!getIsContinue()) return;

        if (isReForNetOK >= 5) {
            complete(new ResponEntity<GoodsBO>().fail(null, ""));
            return;
        }
        
        if (NetworkStateModule.getInstance().getIsNetworkOK()) {
            isReForNetOK++;
            doExecuting(null);
        } else {
            
            if (observerAutoNext != null)
                LinkBus.unregisterReceiver(observerAutoNext);
            LinkBus.registerReceiver(getobserverAutoNext());
        }
    }

    ObserverAutoNext observerAutoNext;

    private ObserverAutoNext getobserverAutoNext() {
        if (observerAutoNext == null) {
            observerAutoNext = new ObserverAutoNext<OnNetworkStateEvent>() {
                @Override
                public void onReceiver(OnNetworkStateEvent data) {
                    if (!getIsContinue()) {
                        LinkBus.unregisterReceiver(this);
                        return;
                    }
                    if (data.extIsNetworkOK) {
                        LinkBus.unregisterReceiver(this);
                        doExecuting(null);
                    }
                }

                @Override
                public Class getBusEventClass() {
                    return OnNetworkStateEvent.class;
                }
            };
        }
        return observerAutoNext;
    }

    @Override
    public boolean onInterceptEnd(boolean isCancel, ResponEntityAbs<GoodsBO> result) {
        if (observerAutoNext != null)
            LinkBus.unregisterReceiver(observerAutoNext);
        return super.onInterceptEnd(isCancel, result);
    }

    
    private static class GoodsTO {

        @SerializedName("rule")
        public String rule;


        @SerializedName("title")
        public String ruleVar; 

        @SerializedName("list")
        public List<GoodsEntity> goodsEntities;
    }

}
